package com.topscore.uke.ui.activities;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.CoordinatorLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.StrikethroughSpan;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.flyco.tablayout.CommonTabLayout;
import com.flyco.tablayout.listener.CustomTabEntity;
import com.flyco.tablayout.listener.OnTabSelectListener;
import com.kingja.loadsir.callback.Callback;
import com.kingja.loadsir.core.LoadService;
import com.kingja.loadsir.core.LoadSir;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.topscore.uke.R;
import com.topscore.uke.entities.ProductDetailBean;
import com.topscore.uke.mvp.contractors.GetProductDetailContractor;
import com.topscore.uke.mvp.presenters.GetProductDetailPresenter;
import com.topscore.uke.ui.ToolBarCompatActivity;
import com.topscore.uke.ui.dialog.ShareDialog;
import com.topscore.uke.ui.fragments.ArrangeFragment;
import com.topscore.uke.ui.fragments.ProductDetailFragment;
import com.topscore.uke.ui.loadsir_callback.ErrorCallBack;
import com.topscore.uke.ui.loadsir_callback.LoadingCallBack;
import com.topscore.uke.utils.DisplayImageOptionsManager;
import com.topscore.uke.utils.WXNativeShareUtil;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

public class ProductDetailActivity extends ToolBarCompatActivity implements GetProductDetailContractor.View, View.OnClickListener {

    @Bind(R.id.product_banner_pager)
    ViewPager productBannerPager;
    @Bind(R.id.cursor_container)
    LinearLayout cursorContainer;
    @Bind(R.id.product_title_tv)
    TextView productTitleTv;
    @Bind(R.id.tab_layout)
    CommonTabLayout tabLayout;
    @Bind(R.id.product_detail_pager)
    ViewPager productDetailPager;
    @Bind(R.id.share_btn)
    LinearLayout shareBtn;
    @Bind(R.id.price_tv)
    TextView priceTv;
    @Bind(R.id.original_price_tv)
    TextView originalPriceTv;
    @Bind(R.id.root_layout)
    CoordinatorLayout rootLayout;

    private ProductDetailFragment mProductDetailFragment;
    private ArrangeFragment mArrangeFragment;
    private List<Fragment> mFragments;
    private FragmentAdapter mDetailPagerAdapter;

    private ShareDialog mShareDialog;

    private ProductDetailBean mDetailBean;

    private final String[] mTabTitles = {"商品详情"
//            , "穿搭建议"
    };

    private ImageView[] mIndicatorViews;
    private ImageView mIndicator;
    private ProductPagerAdapter mProductPagerAdapter;

    private GetProductDetailContractor.Presenter mPresenter;

    private String mProductId;

    private LoadService mLoadService;

//    private final String[] mImages = {"http://ios-setup.oss-cn-beijing.aliyuncs.com/UkeImage_test/bannerOne@2x.png",
//            "http://ios-setup.oss-cn-beijing.aliyuncs.com/UkeImage_test/bannerTwo@2x.png",
//            "http://ios-setup.oss-cn-beijing.aliyuncs.com/UkeImage_test/bannerThree@2x.png",
//            "http://ios-setup.oss-cn-beijing.aliyuncs.com/UkeImage_test/bannerFour@2x.png"};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mProductId = getIntent().getStringExtra("product_id");
        setContentView(R.layout.activity_product_detail);
        ButterKnife.bind(this);
        setCentralTitle("商品详情");
        mPresenter = new GetProductDetailPresenter(mProductId, this);
        initViews();
    }

    private void initViews() {
        mLoadService = LoadSir.getDefault().register(rootLayout, new Callback.OnReloadListener() {
            @Override
            public void onReload(View v) {
                initData();
            }
        });
        mProductDetailFragment = new ProductDetailFragment();
        mArrangeFragment = new ArrangeFragment();
        mFragments = new ArrayList<>();
        mFragments.add(mProductDetailFragment);
//        mFragments.add(mArrangeFragment);
        mDetailPagerAdapter = new FragmentAdapter();
        productDetailPager.setAdapter(mDetailPagerAdapter);
        List<CustomTabEntity> tabEntities = new ArrayList<>();
        for (int i = 0; i < mTabTitles.length; i++) {
            int pos = i;
            CustomTabEntity entity = new CustomTabEntity() {
                @Override
                public String getTabTitle() {
                    return mTabTitles[pos];
                }

                @Override
                public int getTabSelectedIcon() {
                    return 0;
                }

                @Override
                public int getTabUnselectedIcon() {
                    return 0;
                }
            };
            tabEntities.add(entity);
        }
        tabLayout.setTabData((ArrayList<CustomTabEntity>) tabEntities);
        tabLayout.setOnTabSelectListener(new OnTabSelectListener() {
            @Override
            public void onTabSelect(int position) {
                productDetailPager.setCurrentItem(position);
            }

            @Override
            public void onTabReselect(int position) {

            }
        });
        productDetailPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                tabLayout.setCurrentTab(position);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        mProductPagerAdapter = new ProductPagerAdapter();
        productBannerPager.setAdapter(mProductPagerAdapter);
        productBannerPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                for (int i = 0; i < mIndicatorViews.length; i++) {
                    mIndicatorViews[i].setImageResource(R.mipmap.indicator_gray_dot);
                }
                mIndicatorViews[position].setImageResource(R.mipmap.indicator_red_dot);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });

        shareBtn.setOnClickListener(this);
        initData();
    }

    private void initData() {
        mPresenter.getProductDetail();
//        List<String> imageList = new ArrayList<>();
//        for (int i = 0; i < mImages.length; i++) {
//            imageList.add(mImages[i]);
//        }
//        setUpPagerData(imageList);
//        mArrangeFragment.setUpImageData(imageList);
    }

    private void setUpPagerData(List<String> images) {
        mIndicatorViews = new ImageView[images.size()];
        cursorContainer.removeAllViews();
        for (int i = 0; i < images.size(); i++) {
            mIndicator = new ImageView(mContext);
            mIndicator.setAdjustViewBounds(true);
            mIndicator.setScaleType(ImageView.ScaleType.CENTER_CROP);
            mIndicatorViews[i] = mIndicator;
            if (i == 0) {
                mIndicator.setImageResource(R.mipmap.indicator_red_dot);
            } else {
                mIndicator.setImageResource(R.mipmap.indicator_gray_dot);
            }
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            layoutParams.leftMargin = 10;
            layoutParams.rightMargin = 10;
            mIndicator.setLayoutParams(layoutParams);
            cursorContainer.addView(mIndicator);
        }
        mProductPagerAdapter.setPhotoList(images);
    }

    @Override
    public void onGetDetailSuccess(ProductDetailBean detail) {
        setUpPagerData(detail.getMainImage());
        mDetailBean = detail;
        productTitleTv.setText(detail.getTitle());
        mProductDetailFragment.setUpImageData(detail.getDetailImage());
        priceTv.setText("￥" + new DecimalFormat("0.00").format(detail.getPrice()));
        String originPrice = "原价" + "￥" + new DecimalFormat("0.00").format(detail.getPriceTag());
        SpannableString originPriceSpannable = new SpannableString(originPrice);
        originPriceSpannable.setSpan(new StrikethroughSpan(), 0, originPriceSpannable.length(), Spanned.SPAN_INCLUSIVE_INCLUSIVE);
        originalPriceTv.setText(originPriceSpannable);

    }

    @Override
    public void onLoading(String loadingMessage) {
        mLoadService.showCallback(LoadingCallBack.class);
    }

    @Override
    public void onLoadFinished() {
        mLoadService.showSuccess();
    }

    @Override
    public void onFail(int code, String errorMessage) {
        mLoadService.showCallback(ErrorCallBack.class);
        new AlertDialog.Builder(mContext)
                .setMessage(errorMessage)
                .setTitle("错误" + "-" + code)
                .create().show();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.share_btn:
//                if (mShareDialog == null) {
//                    mShareDialog = new ShareDialog(mContext);
//                }
//                mShareDialog.setOnShareSelectedListener(share_media ->
//                        ImageLoader.getInstance().loadImage(mDetailBean.getMainImage().get(0),
//                                DisplayImageOptionsManager.getInstance().getDefaultOptions(),
//                                new ImageLoadingListener() {
//                                    @Override
//                                    public void onLoadingStarted(String s, View view) {
//                                        showLoadingDialog();
//                                    }
//
//                                    @Override
//                                    public void onLoadingFailed(String s, View view, FailReason failReason) {
//                                        dismissLoadingDialog();
//                                    }
//
//                                    @Override
//                                    public void onLoadingComplete(String s, View view, Bitmap bitmap) {
//                                        dismissLoadingDialog();
//                                        new ShareUtil(ProductDetailActivity.this, share_media)
//                                                .setMiniProgram(bitmap,
//                                                        "gh_bc89d7ebfefc",
////                                                        "31219",
//                                                        mProductId,
//                                                        UserInfoManager.getUserInfo().getLoginName(),
//                                                        mDetailBean.getTitle())
//                                                .share();
//                                    }
//
//                                    @Override
//                                    public void onLoadingCancelled(String s, View view) {
//                                        dismissLoadingDialog();
//                                    }
//                                })
//
//                ).show();
                new WXNativeShareUtil(mContext, SendMessageToWX.Req.WXSceneSession)
                        .shareMiniPro(mDetailBean.getMainImage().get(0),
                                mProductId,
                                "gh_bc89d7ebfefc",
                                mDetailBean.getTitle());
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
//        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);//完成回调
    }

    private class FragmentAdapter extends FragmentPagerAdapter {

        public FragmentAdapter() {
            super(ProductDetailActivity.this.getSupportFragmentManager());
        }

        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }

        @Override
        public int getCount() {
            return mFragments.size();
        }
    }

    private class ProductPagerAdapter extends PagerAdapter {

        private List<View> mViewCacheList = new ArrayList<>();

        private List<String> photoList = new ArrayList<>();

        @Override
        public int getCount() {
            return photoList.size();
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            String photo = photoList.get(position);
            View rootView = null;
            ImageView imageView;
            if (mViewCacheList.isEmpty()) {
                rootView = getLayoutInflater().inflate(R.layout.product_photo_pager_item, null);
            } else {
                rootView = mViewCacheList.remove(0);
            }
            imageView = (ImageView) rootView.findViewById(R.id.photo_iv);
            ImageLoader.getInstance().displayImage(photo, imageView, DisplayImageOptionsManager.getInstance().getDefaultOptions());
            container.addView(rootView);
            return rootView;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
//            super.destroyItem(container, position, object);
            View view = (View) object;
            container.removeView(view);
            mViewCacheList.add(view);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        public void setPhotoList(List<String> photoList) {
            this.photoList = photoList;
            notifyDataSetChanged();
        }
    }
}
